package com.houdoudou.customer.buy;

import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.provider.Settings;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.houdoudou.bean.Customer;
import com.houdoudou.bean.Order;
import com.houdoudou.customer.CustomerMainActivity;
import com.houdoudou.customer.R;
import com.houdoudou.customer.common.CommonFunction;
import com.houdoudou.customer.common.Constant;
import com.houdoudou.customer.common.TransPasswordUtil;
import com.houdoudou.customer.common.UniversalHttpPost;
import com.houdoudou.customer.me.SetPaySecretAct;

public class HoudouPayAct extends Activity {


	TextView order,money,acount;
	EditText paysecret;
	Button confirm;
	ProgressBar prgs;
	JSONObject payDuty;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.act_houdoupay);
		payDuty=JSONObject.fromObject(getIntent().getStringExtra("payDuty"));
		order= (TextView) findViewById(R.id.tv_orderid_act_houdoupay);
		money= (TextView) findViewById(R.id.tv_moneyhoudou_act_houdoupay);
		acount= (TextView) findViewById(R.id.tv_acount_act_houdoupay);
		confirm=  (Button) findViewById(R.id.btn_confirm_act_houdoupay);
		paysecret= (EditText) findViewById(R.id.et_paysecret_act_houdoupay);
		prgs= (ProgressBar) findViewById(R.id.prgs_act_houdoupay);
		prgs.setVisibility(View.GONE);
		order.setText(payDuty.getString("toWho"));
		money.setText("￥"+ payDuty.getDouble("money"));		
		acount.setText("账户："+ Constant.customerJO.getString(Customer.TELNUM));
		confirm.setOnClickListener(new View.OnClickListener() {	
			@Override
			public void onClick(View v) {
			if(paysecret.getText().toString().isEmpty()){  
				Toast.makeText(HoudouPayAct.this, "支付密码为空", Toast.LENGTH_SHORT).show(); return;}
			
				JSONObject customerJO= JSONObject.fromObject(Constant.customerJO);
				try {
					String cipherSecret= TransPasswordUtil.encrypt(paysecret.getText().toString());
					customerJO.put(Customer.PAYSECRET, cipherSecret);
			                  	} catch (Exception e) {	e.printStackTrace();}
				
				String[] params= new String[3];
	            params[0]=Constant.BaseUrl+Constant.CustomerUrl;
                params[1]="payOrder"; //PostCod
                JSONObject jsonData=new JSONObject();
	            jsonData.put("customer", customerJO);
	            JSONObject currentOrderJO= new JSONObject();
	            currentOrderJO.put(Order.MONEYCU, payDuty.getDouble("money"));
	            jsonData.put("order",currentOrderJO );
               params[2]=jsonData.toString();
               new HttpPostTaskforPay().execute(params);
               prgs.setVisibility(View.VISIBLE);
			
			}});
	}
	

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if(Constant.customerJO.getString(Customer.PAYSECRET).isEmpty()){
			  Builder b = new AlertDialog.Builder(HoudouPayAct.this).setTitle("问下提示")  
					     .setMessage("亲，您还未设置支付密码，必须先设置支付密码才能使用厚豆账户余额");  
					   b.setPositiveButton("设置支付密码", new DialogInterface.OnClickListener() {  
					    public void onClick(DialogInterface dialog, int whichButton) {  					    	
					    	Intent mIntent = new Intent(HoudouPayAct.this, SetPaySecretAct.class); 
					          startActivity(mIntent);  dialog.cancel(); 
					    }  
					   }).setNeutralButton("放弃支付",new DialogInterface.OnClickListener() {  
						    public void onClick(DialogInterface dialog, int whichButton) {
						    	Intent intent= getIntent(); JSONObject result= new JSONObject();
							       result.put("success", false);
							       result.put("errorInfo", "您已经取消支付");
							       intent.putExtra("result", result.toString());
							    HoudouPayAct.this.setResult(RESULT_OK, intent);
						    	HoudouPayAct.this.finish();
						        
							    }  
					   }).show();  
		}
		
	}


private  class HttpPostTaskforPay extends android.os.AsyncTask<String,String,Map<String,Object>>{

		

		@Override
		protected Map<String,Object> doInBackground(String... params) {
			// TODO Auto-generated method stub
			 Map<String,Object> map = new HashMap<String ,Object>();		
		  map =	UniversalHttpPost.doPost(params);	             
			return map;
		}
		
		@Override
		protected void onPostExecute(Map<String,Object> map) {
		
			
			 System.out.println("-----------onPostExecute()--------------");
			 prgs.setVisibility(View.GONE);
			 String PostResult=(String) map.get("PostResult");		 
			 boolean networkstate=(Boolean) map.get("PostState");
			 if(!networkstate){
				 CommonFunction.alert(HoudouPayAct.this, "支付失败", "无网络连接");return;
		      
			}
			//	Toast.makeText(getActivity(), "服务器返回数据为"+PostResult, Toast.LENGTH_SHORT).show();
				Boolean success=false;
				String errorInfo="";
				JSONObject json = null;
				try{
			     json= JSONObject.fromObject(PostResult);
				 success=json.getBoolean("success");
				 errorInfo=json.getString("errorInfo");	
				}catch(JSONException e){
					 CommonFunction.alert(HoudouPayAct.this, "支付失败", "数据解析错误");return;
				}
										   												      		       
		       if(!success){   CommonFunction.alert(HoudouPayAct.this, "支付失败", errorInfo);return;   }
		       Toast.makeText(HoudouPayAct.this, "支付成功,即将跳转", Toast.LENGTH_SHORT).show(); 
		       Intent intent= getIntent(); JSONObject result= new JSONObject();
		       result.put("success", true);   intent.putExtra("result", result.toString());
		       HoudouPayAct.this.setResult(RESULT_OK, intent);
		       HoudouPayAct.this.finish();
			
		} //onPostExecute
	} //AsyncTask
	
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if(keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN){   
    	 Builder b = new AlertDialog.Builder(HoudouPayAct.this).setTitle("温馨提示")  
			     .setMessage("亲，您还未支付成功，是否放弃支付？");  
			   b.setPositiveButton("放弃", new DialogInterface.OnClickListener() {  
			    public void onClick(DialogInterface dialog, int whichButton) {  					    	
			    	Intent intent= getIntent(); JSONObject result= new JSONObject();
				       result.put("success", false);
				       result.put("errorInfo", "您已经取消支付");
				       intent.putExtra("result", result.toString());
				    HoudouPayAct.this.setResult(RESULT_OK, intent);
			    	HoudouPayAct.this.finish();  dialog.cancel(); 
			    }  
			   }).setNeutralButton("取消",new DialogInterface.OnClickListener() {  
				    public void onClick(DialogInterface dialog, int whichButton) {
				    	dialog.cancel();
				        
					    }  
			   }).show(); 
        return true;   
    }
    return super.onKeyDown(keyCode, event);
}
}
